package com.finance.view;

import com.finance.model.UserAccount;
import com.finance.services.IUserAccountService;
import java.io.Serializable;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

/**
 *
 * @author Visual556
 */
@Controller
@Scope(value = "request")
public class IndexPage implements Serializable {

    private final UserAccount userAccount = new UserAccount();
    private String renterPassword = "";

    public IndexPage() {
    }

    @Autowired
    private IUserAccountService userAccountService;

    @Inject
    private UserAccountSession userAccountSession;

    public UserAccount getUserAccount() {
        return userAccount;
    }

    public String getRenterPassword() {
        return renterPassword;
    }

    public void setRenterPassword(String renterPassword) {
        this.renterPassword = renterPassword;
    }

    public String login() {
        try {
            UserAccount result = userAccountService.login(userAccount);

            userAccountSession.setUsername(result.getUsername());
            FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("username", result.getUsername());
            FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("userAccountEnum", result.getType());
            return "success";
        } catch (Exception ex) {
            return "failure";
        }
    }

    public String register() {
        if (!renterPassword.equals(userAccount.getPassword())) {
            return "failure";
        }
        
        try {
            userAccountService.register(userAccount);
            userAccountSession.setUsername(userAccount.getUsername());
            FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("username", userAccount.getUsername());
            FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("userAccountEnum", userAccount.getType());
            return "success";
        } catch (Exception ex) {
            return "failure";
        }
    }
}
